package cn.tedu.mall.search.service.impl;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.pojo.product.model.Spu;
import cn.tedu.mall.pojo.search.entity.SpuForElastic;
import cn.tedu.mall.product.service.front.IForFrontSpuService;
import cn.tedu.mall.search.repository.SpuRepository;
import cn.tedu.mall.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements ISearchService {
    //远程调用product模块，查询spu列表
    @DubboReference
    private IForFrontSpuService dubboFrontSpuService;
    //加载到ES中，需要使用ElasticSearchRepository提供的方法
    @Autowired
    private SpuRepository spuRepository;

    //以分页形式将数据加载到ES中
    @Override
    public void loadSpuByPage() {
        //页码
        int page = 1;
        //每页条数
        int pageSize = 10;
        //总页数
        int pages = 0;
        do{
            JsonPage<Spu> jsonPage = dubboFrontSpuService.getSpuByPage(page, pageSize);
            List<SpuForElastic> esSpus = new ArrayList<>();
            //我们需要遍历的将spu转成spuForElastic类型
            for (Spu spu : jsonPage.getList()) {
                SpuForElastic spuForElastic = new SpuForElastic();
                BeanUtils.copyProperties(spu,spuForElastic);
                //放入esSpus集合中
                esSpus.add(spuForElastic);
            }
            //执行批量新增数据到ES中
            spuRepository.saveAll(esSpus);
            log.info("成功加载第{}页数据到ES中",page);
            //为下次循环做准备
            pages = jsonPage.getTotalPage();
            page++;
        }while (page<=pages);
    }

    @Override
    public JsonPage<SpuForElastic> search(String keyword, Integer page, Integer pageSize) {
        //SpringDataES中的0才是第一页页码
        Page<SpuForElastic> spuForElastics = spuRepository.querySearch(keyword, PageRequest.of(page - 1, pageSize));
        JsonPage<SpuForElastic> jsonPage = new JsonPage<>();
        jsonPage.setPage(page); //页码
        jsonPage.setPageSize(pageSize); //每页条数
        jsonPage.setTotalPage(spuForElastics.getTotalPages()); //总页数
        jsonPage.setTotal(spuForElastics.getTotalElements()); //总条数
        jsonPage.setList(spuForElastics.getContent()); //分页数据
        //返回jsonPage
        return jsonPage;
    }
}
